module game{
    export class CoreView extends BaseEuiView{
         public btn_home:eui.Button;
         public txt_score:eui.Label;
         public effect:eui.Image;

         private itemList:{[index:number]:McCandy};
         private id:number = 0;

         public constructor($m:BaseController,$parent:eui.Group){
            super($m,$parent);
            this.skinName = "resource/skin/Core.exml";
        }
        
        public initUI():void{
            super.initUI();

            const self = this;
            this.btn_home.addEventListener(egret.TouchEvent.TOUCH_TAP,this.backHomeHandler,this);
        }

        public open(...param:any[]):void {
            super.open(...param);
            egret.Tween.removeTweens(this.effect);
            this.effect.alpha = 0;
            this.itemList = {};
            this.randomCandy();


            this.txt_score.text = gameData.historyScore +"";
      
        }


        private backHomeHandler(){
            //clearAll

            App.ViewManager.close(ViewConst.Core);
            App.ViewManager.open(ViewConst.Home);
        }

        private candyBoxList:string[] = ["boxFirst","boxSecond","boxThree","boxFour","boxFive"];
        private randomCandy(){
            var arr = [];
            this.clearCandy();
            this.itemList = {};
            
            this.isShowMax = false;

            let max = gameData.curmax;
            
            for(var i = 0 ; i < this.candyBoxList.length ; i++){
                for(var j = 0 ; j < 5 ; j++){
                    this.createCandyMC(i,j);
                }
            }

            this.checkAll(true);
        }


        private clearCandy(){
            let dic = this.itemList;
            for(let key in dic){
                let mc = dic[key];
                if(mc){
                    mc.dispose();
                    mc.destroy();
                    mc = null;
                }
            }
            dic = {};
        }


        //清理candy
        // private removeArray = [];
        public removeCandy(mcCandy:McCandy){
            if(!mcCandy) return;

            let checklist = this.checkRound(mcCandy);
            let count = checklist.length;

            //有消掉的
            if(count > 1){
                //把一样的消掉
                for(var i = 0 ; i < count ; i++){
                    var mc:McCandy = checklist[i];
                    if(mc && mc.voCandy.id != mcCandy.voCandy.id){
                        let key = mc.voCandy.row + "_" + mc.voCandy.col;
                        delete this.itemList[key];
                        delete gameData.mapDic[key]
                        mc.dispose();
                    }
                }

                //点击mc+1
                let type =  mcCandy.voCandy.type+1;
                if(type > gameData.curmax){
                    //最大数字改变
                    gameData.curmax  = type;
                    if(type > 15){
                        //大于15个弹提示
                        App.ViewManager.open(ViewConst.GameGoal);
                    }
                }
                mcCandy.voCandy.type = type; 
                mcCandy.setCandyValue(mcCandy.voCandy)
                //check
                this.checkColor();
                
                App.TimerManager.doTimer(300,1,this.restart,this);
                App.TimerManager.doTimer(700,1,this.replenish,this);
            }else{
                //没有可以和的
            }
        }

        private restart(){
            var row = 5;
            var col = 5;
            for(var  j = 0 ; j < row ; j++){
                for (var k = col -1; k >= 0; k--){
                    let mc:McCandy = this.itemList[ j + "_" + k];
                    if(mc){
                        while(this.checkDownMc(mc,mc.voCandy.col +1) == true){
                            mc.voCandy.y += 118;
                            egret.Tween.removeTweens(mc);
                            egret.Tween.get(mc).to({y:mc.voCandy.y},200);
                        }
                    }
                }
            }
        }
        
        //补全
         private replenish(){
            var row = 5;
            var col = 5;
            let max = gameData.curmax;
            for(var  j = 0 ; j < row ; j++){
                for (var k = 0 ; k <col; k++){
                    let mc = this.itemList[ j + "_" + k];
                    if(!mc){
                        this.createCandyMC(j,k);
                    }
                }
            }

            this.checkAll();
        }


        private createCandyMC(i,j){
            let mcCandy = new McCandy();
            let vo = new CandyVO();
            let max = gameData.curmax;
            vo.id = this.id;
            vo.width = 110;
            vo.height = 110;
            vo.row = i;
            vo.col = j;
            vo.type = this.getType(i,j);//Math.floor(Math.random()*max)+1;

            mcCandy.x = 68 + i*118;
            mcCandy.y = 378 + j*118;

            vo.x = mcCandy.x;
            vo.y = mcCandy.y;
            mcCandy.init(vo);

            this.addChild(mcCandy);

            this.id++;
            this.itemList[i+"_"+j] = mcCandy;
            gameData.mapDic[i+"_"+j] = mcCandy.voCandy;

        }

        private isShowMax:boolean = false;
        private getType(i,j){
            let type = 0;
            if(j == 4 && this.isShowMax == false)
            {
                //最后一行肯定会出现1个最大数字
                var key = 0
                if(i== 4){
                    //最后一个还没出现
                    type = gameData.curmax;
                }else{
                    //最后一行生成公式
                    if(Math.random() >0.7){
                        type = gameData.curmax;
                    }else{
                         let min = Math.floor((gameData.curmax-6)/3) + 1;
                        let count = gameData.curmax - min;
                        let probability:number[] = gameData.config[count];

                        let random = Math.random();
                        let pre:number = 0
                        for( key = 0 ; key < count ; key++){
                            let percet = probability[key];
                            let next = pre + percet;
                            if( pre <= random && random <=next){
                                break;
                            }
                            pre += percet;
                        }

                        type = min + key;

                    }
                }

            }else{
                //其他行数
                let min = Math.floor((gameData.curmax-6)/3) + 1;
                let count = gameData.curmax - min;
                let probability:number[] = gameData.config[count];

                let random = Math.random();
                let pre:number = 0
                for(key = 0 ; key < count ; key++){
                    let percet = probability[key];
                    let next = pre + percet;
                   
                    if( pre <= random && random <=next){
                        break;
                    }
                    pre += percet;
                }

                type = min + key;

            }

            if(type == gameData.curmax){
                this.isShowMax = true;
            }

            return type;
        }


        /**********check*************** */
        private checkList:McCandy[];
        private checkRound(mc){
            this.checkList = [];
            this.check(mc);
            return this.checkList;
        }

        private check(mcCandy){
            if(this.checkList.indexOf(mcCandy)>-1) return;
            this.checkList.push(mcCandy);
            let arr = [];
            let type = mcCandy.voCandy.type;

            let row = mcCandy.voCandy.row;
            let preRow  = row - 1;
            let backRow = row + 1;
            let col = mcCandy.voCandy.col;
            let preCol = col - 1;
            let backCol = col + 1;


            let left:McCandy = preRow>-1?this.itemList[preRow + "_" + col]:null;
            let right:McCandy = backRow>-1?this.itemList[backRow + "_" + col]:null;
            let up:McCandy = backCol>-1?this.itemList[row + "_" + backCol]:null;
            let down:McCandy = preCol>-1?this.itemList[row + "_" + preCol]:null;

            if(left && left.voCandy.type == type){
                arr.push(left);
            }

            if(right && right.voCandy.type == type){
                arr.push(right);
            }
            if(up && up.voCandy.type == type){
                arr.push(up);
            }
            if(down && down.voCandy.type == type){
                arr.push(down);
            }

            let count = arr.length;
            for(let i = 0 ; i < count ; i++){
                this.check(arr[i]);
            }
        }

        private checkDownMc(mc:McCandy , col){
             if(col > 4 ) return false;
             var downMC = this.itemList[mc.voCandy.row +"_" + col];
             if(!downMC){
                 let key = mc.voCandy.row +"_" +mc.voCandy.col;
                 delete this.itemList[key] ;
                 delete gameData.mapDic[key] ;
                 mc.voCandy.col = col;
                 key = mc.voCandy.row +"_" +mc.voCandy.col;
                this.itemList[key] = mc;
                gameData.mapDic[key] = mc;
                return true;
             }
             return false;
        }

        private checkColor(){
            var row = 5;
            var col = 5;
            for(var  j = 0 ; j < row ; j++){
                for (var k = 0 ; k <col; k++){
                    let mc:McCandy = this.itemList[ j + "_" + k];
                    if(mc){
                        mc.setCandyValue(mc.voCandy);
                    }
                }
            }
        }

        private _canRemoveDic:{[index:number]:McCandy};
        private checkAll(isRedo = false ){
             egret.Tween.removeTweens(this.effect);
             this.effect.alpha = 0;
            if(this.itemList){
                this._canRemoveDic = {};
                let count = 0;
                for (let key in this.itemList){
                    let mcCandy = this.itemList[key];
                    if(mcCandy){
                        var checklist = this.checkRound(mcCandy);
                        if(checklist.length >= 2){
                            count++;
                            this._canRemoveDic[mcCandy.voCandy.id] = mcCandy;
                        }
                    } 
                }

                if(count < 1 ){
                    //没有道具了
                    for (let key in this.itemList){
                        let mcCandy = this.itemList[key];
                        if(mcCandy){
                            mcCandy.gameOver();
                        }
                     }

                     if(isRedo){
                         App.TimerManager.doTimer(3500,1,this.randomCandy,this);
                     }else{
                         //挂了
                         App.TimerManager.doTimer(1000,1,this.gameOver,this);
                     }
                }else{
                    //check max
                    for (let key in this.itemList){
                        let mcCandy = this.itemList[key];
                        if(mcCandy && mcCandy.voCandy.type == gameData.curmax){
                            var checklist = this.checkRound(mcCandy);
                            if(checklist.length >= 2){
                                this.showMaxEffect();
                                break;
                            }
                        } 
                    }
                }
            }
        }

        private showMaxEffect()
        {
            let _alpha = !this.effect.alpha;
            egret.Tween.removeTweens(this.effect);
            egret.Tween.get(this.effect).to({alpha:_alpha?1:0},200).call(this.showMaxEffect,this);
        }

        private gameOver(){
            App.ViewManager.open(ViewConst.GameOver);
        }

    }
}